#' @export
make_conjoint_analysis <- function() {

box::use(
  data.table,
  estimatr[lm_robust],
  extrafont[loadfonts],
  patchwork[...],
  ggplot2[...],
  showtext,
  stringr[str_extract, str_detect, str_replace],
  lubridate,
  rio[import],
  gtsummary[as_gt, tbl_cross],
  gtExtras[gt_plt_bar_stack],
  gt[...],
  janitor[clean_names],
  forcats[fct_relevel, fct_collapse],
  dplyr[...],
  ./helpers/theme_helpers[conjoint_reshape, plexi, format_si, percent, clean_cj_amce],
  ./helpers/ganter_acp,
  here[here],
  likert[likert],
  data.table[setDT],
  tidyr[pivot_longer, unite],
  modelsummary[modelsummary],
  usethis[ui_done, ui_todo, ui_path, ui_info],
  graphics[par],
  grDevices[cairo_pdf],
  stats[lm, median],
  scales,
  cowplot[plot_grid],
  broom[tidy],
  cregg[cj],
  xtable[xtable],
  stats[pnorm, predict]
)

loadfonts(device = "win")
loadfonts(device = "pdf")
par(family = "CMU Serif")

ui_todo("Starting conjoint analysis.")
ui_info("Figures will be in {ui_path('figs/')}, tabs in {ui_path('tabs/')}. Data in {ui_path('data/')}.")
ui_info("Input data is:")
ui_info("{ui_path('data/arms_conjoint.RDS')} - conjoint data")

# ---------------------------------------------------------------------------- #
#                          prep data for triangulation                         #
# ---------------------------------------------------------------------------- #

df <- readRDS(here("data/arms_conjoint.RDS"))

### Attribute Names

att_names <- c(
  `ATT1` = "Regime Type",
  `ATT2` = "Human Rights \nSituation",
  `ATT3` = "Conflict Situation",
  `ATT4` = "Security Partner",
  `ATT5` = "Trade Relationship",
  `ATT6` = "Economic Value",
  `ATT7` = "Jobs at Risk",
  `ATT8` = "Weapon Type",
  `ATT9` = "Weapon Exports \nof other Countries"
)

## Reshaping and Labelling --------------------------------------

cj_tidy <- conjoint_reshape(df)

# AMCEs Pooled Model --------------------------------------

# Estimating the main model

m1 <-  tidy(lm_robust(data = cj_tidy, y ~ ATT1 + ATT2 + ATT3+ ATT4 + ATT5 + ATT6 + ATT7 + ATT8 + ATT9, clusters = uuid, se_type = "stata"))

m1 <- clean_cj_amce(df = m1, input = cj_tidy)

# Plotting

## Figure 5 ---------

p <- ggplot(m1, aes(y=order,x=estimate)) + xlim(-0.21,0.2) + geom_point(size=2)+ plexi() +
  geom_segment(data=m1, aes(x=conf.low,xend=conf.high, y=order,yend=order)) +
  geom_text(aes(label=ifelse(estimate != 0, round(estimate, digits = 3),"")), vjust = 0, nudge_y = 0.3) +
  facet_grid(attribute~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks=m1$order,labels=m1$term)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("\nAMCE") +
  geom_vline(xintercept = 0,size=.5,colour="black",linetype="dotted") 

ggsave(p, filename = here("figs/fig_5.pdf"), width = 12, height = 15, device = cairo_pdf)


## Leeper, 2019. Marginal Means -------------------------------------- 

m1_mm <- cj(data = cj_tidy, y ~ ATT1 + ATT2 + ATT3+ ATT4 + ATT5 + ATT6 + ATT7 + ATT8 + ATT9, id = ~uuid, estimate = "mm", h0 = 0)

m1_mm <- m1_mm %>% 
  group_by(feature)  %>% 
  arrange(estimate, .by_group = TRUE) %>% 
  ungroup() %>% 
  mutate(order = row_number()*-1) 

m1_mm$order <- factor(m1_mm$order)

### Figure A.4 ---------

p <- ggplot(m1_mm, aes(y=order,x=estimate)) + xlim(0.35,0.65) + geom_point(size=2)+ plexi() +
  geom_segment(data=m1_mm, aes(x=lower,xend=upper, y=order,yend=order)) +
  geom_text(aes(label=ifelse(estimate != 0, round(estimate, digits = 3),"")), vjust = 0, nudge_y = 0.3) +
  facet_grid(feature~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks=m1_mm$order,labels=m1_mm$level)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("\nMarginal Means") +
  geom_vline(xintercept = 0.5,size=.5,colour="black",linetype="dotted") 

ggsave(p, filename = here("figs/fig_a_4.pdf"), width = 12, height = 15, device = cairo_pdf)


## Ganter, 2020. ACP (= Feature Choice Probability, Abramson 2020) --------------------------------------


cj_tidy <- cj_tidy %>% 
  mutate(task_id = sort(rep(seq_len(6 * (nrow(cj_tidy)/(6*2))), 2)))

cj_tidy$CaseID <- with(cj_tidy, match(uuid, unique(uuid)))


conjacp_data <- cj_tidy %>% 
  select(CaseID, y, ATT1 , ATT2 , ATT3, ATT4, ATT5, ATT6,ATT7,ATT8,ATT9, task_id)

conjacp_data <- data.frame(conjacp_data )


results_acp <- ganter_acp$conjacp(y ~ ATT1 + ATT2 + ATT3+ ATT4 + ATT5 + ATT6 + ATT7 + ATT8 + ATT9,
                       data = conjacp_data,
                       tasks = "task_id",
                       subgroups = NULL,
                       id = "CaseID",
                                  estimand = "acp",
                                  by            = NULL,
                                  adjust        = FALSE,
                                  level_weights = NULL,
                                  condition     = NULL,
                                  subset        = NULL
)

estimates <- results_acp$estimates
se        <- sqrt(diag(results_acp$vcov))
z <- estimates/se

out_table <- data.frame(term = gsub("ATT[1-9].", "", names(estimates)),
                        attribute     = as.factor(str_extract(names(estimates), ".+?(?=\\.)")),
                        estimate = estimates,
                        se       = se,
                        z = z,
                        p =  2*pnorm(abs(estimates/se), lower.tail = FALSE),
                        conf.low =  estimates - 1.96 * se, 
                        conf.high = estimates + 1.96 * se)

out_table <- out_table %>% 
  group_by(attribute)  %>% 
  arrange(estimate, .by_group = TRUE) %>% 
  ungroup() %>% 
  mutate(order = row_number()*-1) 

out_table$order <- factor(out_table$order)

### Figure A.6 ---------

p <- ggplot(out_table, aes(y=order,x=estimate)) + xlim(-0.2,0.2) + geom_point(size=2)+ plexi() +
  geom_segment(data=out_table, aes(x=conf.low,xend=conf.high, y=order,yend=order)) +
  geom_text(aes(label=ifelse(estimate != 0, round(estimate, digits = 3),"")), vjust = 0, nudge_y = 0.3) +
  facet_grid(attribute~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks=out_table$order,labels=out_table$term)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("\nACP") +
  geom_vline(xintercept = 0,size=.5,colour="black",linetype="dotted") 

ggsave(p, filename = here("figs/fig_a_6.pdf"), width = 12, height = 15, device = cairo_pdf)



### Figure A.5 ---------

m1_rating <- tidy(lm_robust(data = cj_tidy, y_rating ~ ATT1 + 
                              ATT2 + ATT3+ ATT4 + ATT5 + ATT6 + 
                              ATT7 + ATT8 + ATT9))


# m1_rating_cl <- tidy(lm_robust(data = cj_tidy, y_rating ~ ATT1 + 
#                               ATT2 + ATT3+ ATT4 + ATT5 + ATT6 + 
#                               ATT7 + ATT8 + ATT9, clusters = uuid, method = "stata"))


m1_rating <- clean_cj_amce(df = m1_rating, input = cj_tidy)

# Plotting

p <- ggplot(m1_rating, aes(y=order,x=estimate)) + xlim(-0.6,0.3) + geom_point(size=2)+ plexi() +
  geom_segment(data=m1_rating, aes(x=conf.low,xend=conf.high, y=order,yend=order)) +
  geom_text(aes(label=ifelse(estimate != 0, round(estimate, digits = 3),"")), vjust = 0, nudge_y = 0.3) +
  facet_grid(attribute~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks=m1_rating$order,labels=m1_rating$term)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("\nAMCE") +
  geom_vline(xintercept = 0,size=.5,colour="black",linetype="dotted") 

ggsave(filename = here("figs/fig_a_5.pdf"), width = 12, height = 15, device = cairo_pdf)



# Effect Heterogeneity: Germany/France --------------------------------------

### CAMCEs: Germany/France

de <- cj_tidy %>% 
  filter(hCountry=="Germany")

fr <- cj_tidy %>% 
  filter(hCountry=="France")

m2 <-   tidy(lm_robust(data = de, y ~ ATT1 + ATT2 + ATT3+ ATT4 + ATT5 + ATT6 + ATT7 + ATT8 + ATT9, clusters = uuid, se_type = "stata"))

m2 <- clean_cj_amce(df = m2, input = cj_tidy)

m3 <-  tidy(lm_robust(data = fr, y ~ ATT1 + ATT2 + ATT3+ ATT4 + ATT5 + ATT6 + ATT7 + ATT8 + ATT9, clusters = uuid, se_type = "stata"))

m3 <- clean_cj_amce(df = m3, input = cj_tidy)

m3 <- m3 %>% 
  arrange(match(m2$term, m3$term)) %>% 
  mutate(order = row_number()*-1)

cj_tidy <- cj_tidy %>% 
  mutate(de = ifelse(hCountry == "Germany", 1, 0))

cj_tidy$de <- factor(cj_tidy$de)

# Differences in CAMCEs

m4 <-  tidy(lm_robust(data = cj_tidy, y ~ ATT1*de + ATT2*de + ATT3*de 
                      + ATT4*de + ATT5*de + ATT6*de + ATT7*de + ATT8*de + ATT9*de, clusters = uuid, se_type = "stata"))


# m4 <-  tidy(lm_robust(data = cj_tidy, y ~ ATT1*de + ATT2*de + ATT3*de 
#                       + ATT4*de + ATT5*de + ATT6*de + ATT7*de + ATT8*de + ATT9*de,  cluster = uuid, method = "stata"))

df  <- setDT(m4)
m4 <- m4[term != "(Intercept)"]
m4$attribute <- (str_extract(m4$term, "ATT[1-9]"))
m4$term <- gsub("ATT[1-9]", "", m4$term)
m4 <- m4[grepl("de1:", m4$term) | term == "Not democratically elected:de1",]
m4$term <- gsub("de1:", "", m4$term)
m4$term <- gsub("Not democratically elected:de1", "Not democratically elected", m4$term)


factors <- pivot_longer(cj_tidy, ATT1:ATT9, names_to="attribute", values_to="term") %>% 
  select(term,attribute) %>% 
  distinct() %>% 
  arrange(attribute, term)


m4 <- merge(m4,factors,  by = c("attribute", "term"), all = TRUE)
m4[["estimate"]][is.na(m4[["estimate"]])] <- 0
m4[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m4[estimate == 0, term := paste(term, ")", sep = "")]

  
  m4 <- m4[match(m2$term, m4$term),]
  
  m4 <- m4 %>% 
    mutate(order = row_number()*-1)
  
  m4$order <- factor(m4$order)
  
  
## Figure A.11 ---------

p2 <- ggplot(m2, aes(y=order,x=estimate)) + xlim(-0.25,0.25) + geom_point(size=2)+ plexi() +
  geom_segment(data=m2, aes(x=conf.low,xend=conf.high, y=order,yend=order)) +
  geom_text(aes(label=ifelse(estimate != 0, round(estimate, digits = 3),"")), vjust = 0, nudge_y = 0.3) + 
  facet_grid(attribute~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks=m2$order,labels=m2$term)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("") +
  geom_vline(xintercept = 0,size=.5,colour="black",linetype="dotted") + theme(
    strip.background = element_blank(),
    strip.text.y = element_blank()
  )


p3 <- ggplot(m3, aes(y=order,x=estimate)) + xlim(-0.25,0.25) + geom_point(size=2)+ plexi() +
  geom_segment(data=m3, aes(x=conf.low,xend=conf.high, y=order,yend=order)) +
  geom_text(aes(label=ifelse(estimate != 0, round(estimate, digits = 3),"")), vjust = 0, nudge_y = 0.3) +
  facet_grid(attribute~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks=m3$order,labels=m3$term)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("\nAMCE") +
  geom_vline(xintercept = 0,size=.5,colour="black",linetype="dotted") + theme(axis.text.y = element_blank(),
                                                                              axis.ticks.y = element_blank(),
                                                                              axis.title.y = element_blank() ) +
  theme(
    strip.background = element_blank(),
    strip.text.y = element_blank()
  )


p4 <- ggplot(m4, aes(y=order,x=estimate)) + xlim(-0.25,0.25) + geom_point(size=2)+ plexi() +
  geom_segment(data=m4, aes(x=conf.low,xend=conf.high, y=order,yend=order)) +
  geom_text(aes(label=ifelse(estimate != 0, round(estimate, digits = 3),"")), vjust = 0, nudge_y = 0.3) +
  facet_grid(attribute~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks=m4$order,labels=m4$term)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("") +
  geom_vline(xintercept = 0,size=.5,colour="black",linetype="dotted") + theme(axis.text.y = element_blank(),
                                                                              axis.ticks.y = element_blank(),
                                                                              axis.title.y = element_blank() )


final = p2 + ggtitle("GER") + p3 + ggtitle("FR") + p4 + ggtitle("Difference in CAMCEs (GER-FR)")

ggsave(final, filename = here("figs/fig_a_11.pdf"), width = 18, height = 11, device = cairo_pdf)

### Differences in marginal means

cj_tidy_recode <- cj_tidy
cj_tidy_recode$hCountry = factor(cj_tidy_recode$hCountry,levels(cj_tidy_recode$hCountry)[c(2,1)])

mm_diff <- cj(data = cj_tidy_recode, y ~ ATT1 + ATT2 + ATT3+ ATT4 + ATT5 + ATT6 + ATT7 + ATT8 + ATT9, id = ~uuid, by = ~hCountry, estimate = "mm_differences", h0 = 0)

mm_de <- cj(data = de, y ~ ATT1 + ATT2 + ATT3+ ATT4 + ATT5 + ATT6 + ATT7 + ATT8 + ATT9, id = ~uuid, estimate = "mm", h0 = 0.5)

mm_fr  <-  cj(data = fr, y ~ ATT1 + ATT2 + ATT3+ ATT4 + ATT5 + ATT6 + ATT7 + ATT8 + ATT9, id = ~uuid, estimate = "mm", h0 = 0.5)


mm_de <- mm_de %>% 
  group_by(feature)  %>% 
  ungroup() %>% 
  mutate(order = row_number()*-1) 
mm_de$order <- factor(mm_de$order)

mm_fr<- mm_fr%>% 
  group_by(feature)  %>% 
  ungroup() %>% 
  mutate(order = row_number()*-1) 


mm_diff <- mm_diff %>% 
  group_by(feature)  %>% 
  ungroup() %>% 
  mutate(order = row_number()*-1) 
mm_diff$order <- factor(mm_diff$order)


mm_de <- mm_de %>% 
  mutate(cond = "Germany")

mm_fr<- mm_fr%>% 
  mutate(cond = "France")

mm_defr <- rbind(mm_de, mm_fr)

mm_defr$cond <- factor(mm_defr$cond)

## Figure 9 ----------------------

p <- ggplot(mm_defr, aes(y=order,x=estimate, shape = cond)) + xlim(0.35, 0.65) + geom_point(size=2, position = position_dodge(width=-1)) + plexi() +
  geom_linerange(data=mm_defr, aes(xmin=lower,xmax=upper, y=order), position = position_dodge(width=-1), key_glyph = "path") +
  facet_grid(feature~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks=mm_defr$order,labels=mm_defr$level)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("") +
  geom_vline(xintercept = 0.5,size=.5,colour="black",linetype="dotted") + theme(
    strip.background = element_blank(),
    strip.text.y = element_blank()
  ) 


p3 <- ggplot(mm_diff, aes(y=order,x=estimate)) + xlim(-0.1,0.1) + geom_point(size=2)+ plexi() +
  geom_segment(data=mm_diff, aes(x=lower,xend=upper, y=order,yend=order)) +
  facet_grid(feature~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("\nAMCE") +
  geom_vline(xintercept = 0,size=.5,colour="black",linetype="dotted") +
  scale_y_discrete(breaks=mm_diff$order,labels=mm_diff$level)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("")  +
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        axis.title.y = element_blank())


final = p + theme(legend.title = element_blank(), 
          legend.direction = "vertical",
          legend.position = "bottom",
          legend.justification="left",
          legend.key.height = unit(1, "cm"),
          legend.spacing.y = unit(-0.8, 'cm')) + p3 + ggtitle("Difference in MMs (GER - FR)")

ggsave(final, filename = here("figs/fig_7.pdf"),  width = 11, height = 8, device = cairo_pdf)


## Rating MMs

mm_diff <- cj(data = cj_tidy, y_rating ~ ATT1 + ATT2 + ATT3+ ATT4 + ATT5 + ATT6 + ATT7 + ATT8 + ATT9, id = ~uuid, by = ~hCountry, estimate = "mm_differences", h0 = 0)

mm_de <- cj(data = de, y_rating ~ ATT1 + ATT2 + ATT3+ ATT4 + ATT5 + ATT6 + ATT7 + ATT8 + ATT9, id = ~uuid, estimate = "mm", h0 = 0.5)

mm_fr  <-  cj(data = fr, y_rating ~ ATT1 + ATT2 + ATT3+ ATT4 + ATT5 + ATT6 + ATT7 + ATT8 + ATT9, id = ~uuid, estimate = "mm", h0 = 0.5)


mm_de <- mm_de %>% 
  group_by(feature)  %>% 
  ungroup() %>% 
  mutate(order = row_number()*-1) 
mm_de$order <- factor(mm_de$order)

mm_fr<- mm_fr%>% 
  group_by(feature)  %>% 
  ungroup() %>% 
  mutate(order = row_number()*-1)

mm_diff <- mm_diff %>% 
  group_by(feature)  %>% 
  ungroup() %>% 
  mutate(order = row_number()*-1) 
mm_diff$order <- factor(mm_diff$order)


mm_de <- mm_de %>% 
  mutate(cond = "Germany")

mm_fr<- mm_fr%>% 
  mutate(cond = "France")

mm_defr <- rbind(mm_de, mm_fr)

mm_defr$cond <- factor(mm_defr$cond)


# print(xtable(m_int), include.rownames=FALSE)

## Figure A.10 ----------------------

p <- ggplot(mm_defr, aes(y=order,x=estimate, shape = cond)) + xlim(2.5, 4) + geom_point(size=2, position = position_dodge(width=-1)) + plexi() +
  geom_linerange(data=mm_defr, aes(xmin=lower,xmax=upper, y=order), position = position_dodge(width=-1), key_glyph = "path") +
  facet_grid(feature~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks=mm_defr$order,labels=mm_defr$level)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("") +
  geom_vline(xintercept = 0.5,size=.5,colour="black",linetype="dotted") + theme(
    strip.background = element_blank(),
    strip.text.y = element_blank()
  ) 



p3 <- ggplot(mm_diff, aes(y=order,x=estimate)) + xlim(-0.5,1) + geom_point(size=2)+ plexi() +
  geom_segment(data=mm_diff, aes(x=lower,xend=upper, y=order,yend=order)) +
  facet_grid(feature~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("\nAMCE") +
  geom_vline(xintercept = 0,size=.5,colour="black",linetype="dotted") +
  scale_y_discrete(breaks=mm_diff$order,labels=mm_diff$level)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("")  +
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        axis.title.y = element_blank())


final = p + theme(legend.title = element_blank(), 
          legend.direction = "vertical",
          legend.position = "bottom",
          legend.justification="left",
          legend.key.height = unit(1, "cm"),
          legend.spacing.y = unit(-0.8, 'cm')) + p3 + ggtitle("Difference in MMs (FR - GER)")

ggsave(final, filename = here("figs/fig_a_10.pdf"),  width = 11, height = 8, device = cairo_pdf)


# Effect Heterogeneity: Treatment Interactions --------------------------------------

#  (AMCE| Unkown) - (AMCE| International Competitors)

int <- cj_tidy %>%
  mutate(ATT9 = fct_collapse(ATT9, Unknown = "Unknown", "International Competitors" = c("NATO partners (USA, UK, {France/Germany})", "{France/Germany}", "China and Russia")))

int1 <- cj_tidy %>%
  filter(ATT9 == "Unknown")

int2 <- int %>%
  filter(ATT9 == "International Competitors")

m_int_1 <- tidy(lm_robust(data = int1, y ~ ATT5 + ATT6 + ATT7, clusters = uuid, 
                          se_type = "stata"))


m_int_1 <- m_int_1 %>% 
  filter(term != "(Intercept)") %>% 
  select(term, estimate, conf.low, conf.high)


m_int_2 <- tidy(lm_robust(data = int2, y ~ ATT5 + ATT6 + ATT7, clusters = uuid, 
                          se_type = "stata"))


m_int_2 <- m_int_2 %>% 
  filter(term != "(Intercept)") %>% 
  select(term, estimate, conf.low, conf.high)

m_int <- tidy(lm_robust(data = int, y ~ ATT5*ATT9 + ATT6*ATT9 + ATT7*ATT9, clusters = uuid, 
                        se_type = "stata"))


m_int <- setDT(m_int)
m_int <- m_int[grepl("International Competitors", m_int$term, fixed = T)]
m_int <- m_int[grepl(":", m_int$term),]
m_int$term <- gsub("ATT9International Competitors:", "", m_int$term, fixed = T)
m_int$term <- gsub("ATT5Little trade of goods:ATT9International Competitors", "ATT5Little trade of goods", m_int$term, fixed = T)


m_int$attribute <- (str_extract(m_int$term, "ATT[1-9]"))
m_int$term <- gsub("ATT[1-9]", "", m_int$term)


factors <- pivot_longer(int, c("ATT5", "ATT6", "ATT7"), names_to="attribute", values_to="term") %>% 
  select(term,attribute) %>% 
  distinct() %>% 
  arrange(attribute, term)


m_int <- merge(m_int,factors,  by = c("attribute", "term"), all = TRUE)
m_int[["estimate"]][is.na(m_int[["estimate"]])] <- 0
m_int <- setDT(m_int)
m_int[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int[estimate == 0, term := paste(term, ")", sep = "")]


m_int_1$attribute <- (str_extract(m_int_1$term, "ATT[1-9]"))
m_int_1$term <- gsub("ATT[1-9]", "", m_int_1$term)

m_int_1 <- merge(m_int_1,factors,  by = c("attribute", "term"), all = TRUE)
m_int_1[["estimate"]][is.na(m_int_1[["estimate"]])] <- 0
m_int_1 <- setDT(m_int_1)
m_int_1[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int_1[estimate == 0, term := paste(term, ")", sep = "")]


m_int_2$attribute <- (str_extract(m_int_2$term, "ATT[1-9]"))
m_int_2$term <- gsub("ATT[1-9]", "", m_int_2$term)

m_int_2 <- merge(m_int_2,factors,  by = c("attribute", "term"), all = TRUE)
m_int_2[["estimate"]][is.na(m_int_2[["estimate"]])] <- 0
m_int_2 <- setDT(m_int_2)
m_int_2[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int_2[estimate == 0, term := paste(term, ")", sep = "")]


m_int_2 <- m_int_2 %>%
  arrange(match(m_int_2$term, m_int_1$term)) %>%
  mutate(order = row_number() * -1)

m_int_1 <- m_int_1 %>%
  arrange(match(m_int_1$term, m_int_1$term)) %>%
  mutate(order = row_number() * -1)

m_int <- m_int %>% 
  arrange(match(m_int$term, m_int_1$term)) %>% 
  mutate(order = row_number()*-1)


m_int_1 <- m_int_1 %>% 
  mutate(cond = "AMCE|Unknown")

m_int_2 <- m_int_2 %>% 
  mutate(cond = "AMCE|International Competitors")

m_int_cond <- rbind(m_int_1, m_int_2)

m_int_cond$cond <- factor(m_int_cond$cond)

m_int_cond$order <- factor(m_int_cond$order)
m_int$order <- factor(m_int$order)

# print(xtable(m_int), include.rownames=FALSE)

## Figure 6a  ----------------------

p <- ggplot(m_int_cond, aes(y=order,x=estimate, shape = cond)) + xlim(-0.25,0.15) + geom_point(size=2, position = position_dodge(width=-1)) + plexi() +
  geom_linerange(data=m_int_cond, aes(xmin=conf.low,xmax=conf.high, y=order), position = position_dodge(width=-1), key_glyph = "path") +
  facet_grid(attribute~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks=m_int_cond$order,labels=m_int_cond$term)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("") +
  geom_vline(xintercept = 0,size=.5,colour="black",linetype="dotted") + theme(
    strip.background = element_blank(),
    strip.text.y = element_blank()
  ) 

p3 <- ggplot(m_int, aes(y = order, x = estimate)) +
  xlim(-0.1, 0.1) +
  geom_point(size = 2) +
  plexi() +
  geom_segment(data = m_int, aes(x = conf.low, xend = conf.high, y = order, yend = order)) +
  facet_grid(attribute ~ ., scales = "free_y", space = "free", labeller = as_labeller(att_names)) +
  theme(strip.text.y = element_text(angle = 0)) +
  xlab("\nAMCE") +
  geom_vline(xintercept = 0, size = .5, colour = "black", linetype = "dotted") +
  scale_y_discrete(breaks = m_int$order, labels = m_int$term) +
  ylab("") +
  theme(strip.text.y = element_text(angle = 0)) +
  xlab("") +
  theme(
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank(),
    axis.title.y = element_blank()
  ) 

p_int_other_c <- p + theme(legend.title = element_blank(), 
          legend.direction = "vertical",
          plot.title = element_text(vjust = -4),
          legend.position = "bottom",
          legend.justification="left",
          legend.key.height = unit(1, "cm"),
          legend.spacing.y = unit(-0.8, 'cm')) + p3 + labs(subtitle = "Interaction") + plot_annotation(
  title ="Panel a) Moderation of economic attributes by any international competition", theme = plexi())

ggsave(p_int_other_c, filename = here("figs/fig_6_a.pdf"), width = 10, height = 6, device = cairo_pdf)


# (AMCE| Unkown) - (AMCE| China and Russia)

int1 <- cj_tidy %>%
  filter(ATT9 == "Unknown")

int2 <- cj_tidy %>%
  filter(ATT9 == "China and Russia")


m_int_1 <- tidy(lm_robust(
  data = int1, y ~ ATT1 + ATT2 + ATT3, clusters = uuid,
  se_type = "stata"
))


m_int_1 <- m_int_1 %>%
  filter(term != "(Intercept)") %>%
  select(term, estimate, conf.low, conf.high)


m_int_2 <- tidy(lm_robust(
  data = int2, y ~ ATT1 + ATT2 + ATT3, clusters = uuid,
  se_type = "stata"
))


m_int_2 <- m_int_2 %>%
  filter(term != "(Intercept)") %>%
  select(term, estimate, conf.low, conf.high)

m_int <- tidy(lm_robust(
  data = cj_tidy, y ~ ATT1 * ATT9 + ATT2 * ATT9 +
    ATT3 * ATT9, clusters = uuid,
  se_type = "stata"
))

m_int <- setDT(m_int)
m_int <- m_int[grepl("ATT9China and Russia", m_int$term, fixed = T)]
m_int <- m_int[grepl(":", m_int$term), ]
m_int$term <- gsub("ATT9China and Russia:", "", m_int$term, fixed = T)
m_int$term <- gsub("ATT1Not democratically elected:ATT9China and Russia", "ATT1Not democratically elected", m_int$term, fixed = T)


m_int$attribute <- (str_extract(m_int$term, "ATT[1-9]"))
m_int$term <- gsub("ATT[1-9]", "", m_int$term)


factors <- pivot_longer(cj_tidy, c("ATT1", "ATT2", "ATT3"), names_to = "attribute", values_to = "term") %>%
  select(term, attribute) %>%
  distinct() %>%
  arrange(attribute, term)


m_int <- merge(m_int, factors, by = c("attribute", "term"), all = TRUE)
m_int[["estimate"]][is.na(m_int[["estimate"]])] <- 0
m_int <- setDT(m_int)
m_int[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int[estimate == 0, term := paste(term, ")", sep = "")]


m_int_1$attribute <- (str_extract(m_int_1$term, "ATT[1-9]"))
m_int_1$term <- gsub("ATT[1-9]", "", m_int_1$term)

m_int_1 <- merge(m_int_1, factors, by = c("attribute", "term"), all = TRUE)
m_int_1[["estimate"]][is.na(m_int_1[["estimate"]])] <- 0
m_int_1 <- setDT(m_int_1)
m_int_1[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int_1[estimate == 0, term := paste(term, ")", sep = "")]


m_int_1 <- m_int_1 %>%
  mutate(abs = abs(estimate)) %>%
  group_by(attribute) %>%
  arrange(abs, .by_group = TRUE) %>%
  ungroup() %>%
  mutate(order = row_number() * -1) %>%
  select(-abs)

m_int_2$attribute <- (str_extract(m_int_2$term, "ATT[1-9]"))
m_int_2$term <- gsub("ATT[1-9]", "", m_int_2$term)

m_int_2 <- merge(m_int_2, factors, by = c("attribute", "term"), all = TRUE)
m_int_2[["estimate"]][is.na(m_int_2[["estimate"]])] <- 0
m_int_2 <- setDT(m_int_2)
m_int_2[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int_2[estimate == 0, term := paste(term, ")", sep = "")]


m_int_2 <- m_int_2 %>%
  arrange(match(m_int_2$term, m_int_1$term)) %>%
  mutate(order = row_number() * -1)

m_int <- m_int %>%
  arrange(match(m_int$term, m_int_1$term)) %>%
  mutate(order = row_number() * -1)


m_int_1 <- m_int_1 %>%
  mutate(cond = "Unknown")

m_int_2 <- m_int_2 %>%
  mutate(cond = "China and Russia")

m_int_cond <- rbind(m_int_1, m_int_2)

m_int_cond$cond <- factor(m_int_cond$cond)

m_int_cond$order <- factor(m_int_cond$order)
m_int$order <- factor(m_int$order)

# print(xtable(m_int), include.rownames=FALSE)

## Figure 6b ----------------------

p <- ggplot(m_int_cond, aes(y = order, x = estimate, shape = cond)) +
  xlim(-0.25, 0.15) +
  geom_point(size = 2, position = position_dodge(width = -1)) +
  plexi() +
  geom_linerange(data = m_int_cond, aes(xmin = conf.low, xmax = conf.high, y = order), position = position_dodge(width = -1), key_glyph = "path") +
  facet_grid(attribute ~ ., scales = "free_y", space = "free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks = m_int_cond$order, labels = m_int_cond$term) +
  ylab("") +
  theme(strip.text.y = element_text(angle = 0)) +
  xlab("") +
  geom_vline(xintercept = 0, size = .5, colour = "black", linetype = "dotted") +
  theme(
    strip.background = element_blank(),
    strip.text.y = element_blank()
  )

p3 <- ggplot(m_int, aes(y = order, x = estimate)) +
  xlim(-0.1, 0.1) +
  geom_point(size = 2) +
  plexi() +
  geom_segment(data = m_int, aes(x = conf.low, xend = conf.high, y = order, yend = order)) +
  facet_grid(attribute ~ ., scales = "free_y", space = "free", labeller = as_labeller(att_names)) +
  theme(strip.text.y = element_text(angle = 0)) +
  xlab("\nAMCE") +
  geom_vline(xintercept = 0, size = .5, colour = "black", linetype = "dotted") +
  scale_y_discrete(breaks = m_int$order, labels = m_int$term) +
  ylab("") +
  theme(strip.text.y = element_text(angle = 0)) +
  xlab("") +
  theme(
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank(),
    axis.title.y = element_blank()
  ) 


p_china <- p + theme(
  legend.title = element_blank(),
  legend.direction = "vertical",
  legend.position = "bottom",
  legend.justification = "left",
  legend.key.height = unit(1, "cm"),
  legend.spacing.y = unit(-0.8, "cm")
) + p3 + ggtitle("Interaction") + plot_annotation(title = "Panel b) Moderation of country and conflict attributes by competition from adversaries", theme = plexi())

ggsave(p_china, filename = here("figs/fig_6_b.pdf"), width = 10, height = 6, device = cairo_pdf)

# (AMCE| Democratically elected) - (AMCE| Not democratically elected)

int1 <- cj_tidy %>%
  filter(ATT1 == "Democratically elected")

int2 <- cj_tidy %>%
  filter(ATT1 == "Not democratically elected")


m_int_1 <- tidy(lm_robust(
  data = int1, y ~ ATT4, clusters = uuid,
  se_type = "stata"
))


m_int_1 <- m_int_1 %>%
  filter(term != "(Intercept)") %>%
  select(term, estimate, conf.low, conf.high)


m_int_2 <- tidy(lm_robust(
  data = int2, y ~ ATT4, clusters = uuid,
  se_type = "stata"
))


m_int_2 <- m_int_2 %>%
  filter(term != "(Intercept)") %>%
  select(term, estimate, conf.low, conf.high)

m_int <- tidy(lm_robust(
  data = cj_tidy, y ~ ATT4 * ATT1, clusters = uuid,
  se_type = "stata"
))

m_int <- setDT(m_int)
m_int <- m_int[grepl(":", m_int$term), ]
m_int$term <- gsub(":ATT1Not democratically elected", "", m_int$term, fixed = T)


m_int$attribute <- (str_extract(m_int$term, "ATT[1-9]"))
m_int$term <- gsub("ATT[1-9]", "", m_int$term)


factors <- pivot_longer(cj_tidy, c("ATT4"), names_to = "attribute", values_to = "term") %>%
  select(term, attribute) %>%
  distinct() %>%
  arrange(attribute, term)


m_int <- merge(m_int, factors, by = c("attribute", "term"), all = TRUE)
m_int[["estimate"]][is.na(m_int[["estimate"]])] <- 0
m_int <- setDT(m_int)
m_int[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int[estimate == 0, term := paste(term, ")", sep = "")]


m_int_1$attribute <- (str_extract(m_int_1$term, "ATT[1-9]"))
m_int_1$term <- gsub("ATT[1-9]", "", m_int_1$term)

m_int_1 <- merge(m_int_1, factors, by = c("attribute", "term"), all = TRUE)
m_int_1[["estimate"]][is.na(m_int_1[["estimate"]])] <- 0
m_int_1 <- setDT(m_int_1)
m_int_1[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int_1[estimate == 0, term := paste(term, ")", sep = "")]


m_int_1 <- m_int_1 %>%
  mutate(abs = abs(estimate)) %>%
  group_by(attribute) %>%
  arrange(abs, .by_group = TRUE) %>%
  ungroup() %>%
  mutate(order = row_number() * -1) %>%
  select(-abs)

m_int_2$attribute <- (str_extract(m_int_2$term, "ATT[1-9]"))
m_int_2$term <- gsub("ATT[1-9]", "", m_int_2$term)

m_int_2 <- merge(m_int_2, factors, by = c("attribute", "term"), all = TRUE)
m_int_2[["estimate"]][is.na(m_int_2[["estimate"]])] <- 0
m_int_2 <- setDT(m_int_2)
m_int_2[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int_2[estimate == 0, term := paste(term, ")", sep = "")]


m_int_2 <- m_int_2 %>%
  arrange(match(m_int_2$term, m_int_1$term)) %>%
  mutate(order = row_number() * -1)

m_int <- m_int %>%
  arrange(match(m_int$term, m_int_1$term)) %>%
  mutate(order = row_number() * -1)


m_int_1 <- m_int_1 %>%
  mutate(cond = "Democratically elected")

m_int_2 <- m_int_2 %>%
  mutate(cond = "Not democratically elected")

m_int_cond <- rbind(m_int_1, m_int_2)

m_int_cond$cond <- factor(m_int_cond$cond)

m_int_cond$order <- factor(m_int_cond$order)
m_int$order <- factor(m_int$order)

# print(xtable(m_int), include.rownames=FALSE)

## Figure 6d ----------------------

p <- ggplot(m_int_cond, aes(y = order, x = estimate, shape = cond)) +
  xlim(-0.25, 0.15) +
  geom_point(size = 2, position = position_dodge(width = -1)) +
  plexi() +
  geom_linerange(data = m_int_cond, aes(xmin = conf.low, xmax = conf.high, y = order), position = position_dodge(width = -1), key_glyph = "path") +
  facet_grid(attribute ~ ., scales = "free_y", space = "free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks = m_int_cond$order, labels = m_int_cond$term) +
  ylab("") +
  theme(strip.text.y = element_text(angle = 0)) +
  xlab("") +
  geom_vline(xintercept = 0, size = .5, colour = "black", linetype = "dotted") +
  theme(
    strip.background = element_blank(),
    strip.text.y = element_blank()
  )

p


p3 <- ggplot(m_int, aes(y = order, x = estimate)) +
  xlim(-0.1, 0.1) +
  geom_point(size = 2) +
  plexi() +
  geom_segment(data = m_int, aes(x = conf.low, xend = conf.high, y = order, yend = order)) +
  facet_grid(attribute ~ ., scales = "free_y", space = "free", labeller = as_labeller(att_names)) +
  theme(strip.text.y = element_text(angle = 0)) +
  xlab("\nAMCE") +
  geom_vline(xintercept = 0, size = .5, colour = "black", linetype = "dotted") +
  scale_y_discrete(breaks = m_int$order, labels = m_int$term) +
  ylab("") +
  theme(strip.text.y = element_text(angle = 0)) +
  xlab("") +
  theme(
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank(),
    axis.title.y = element_blank()
  ) 

p_democ <- p + theme(
  legend.title = element_blank(),
  legend.direction = "vertical",
  legend.position = "bottom",
  legend.justification = "left",
  legend.key.height = unit(1, "cm"),
  legend.spacing.y = unit(-0.8, "cm")
)  + p3 + ggtitle("Interaction") + plot_annotation(title = "Panel d) Moderation of strategic partnership by democratic regime", theme = plexi())

ggsave(p_democ, filename = here("figs/fig_6_d.pdf"), width = 8, height = 3, device = cairo_pdf)

# (AMCE| rightful) - (AMCE| Not rightful)

int1 <- cj_tidy %>%
  filter(ATT1 == "Democratically elected" & ATT2 == "Human rights respected")

int2 <- cj_tidy %>%
  filter(ATT1 == "Not democratically elected" & ATT2 == "Dissidents persecuted/incarcerated/tortured")

int3 <- cj_tidy %>%
  mutate(rightful_regime = case_when(
    ATT1 == "Democratically elected" & ATT2 == "Human rights respected" ~ "Rightful regime",
    ATT1 == "Not democratically elected" & ATT2 == "Dissidents persecuted/incarcerated/tortured" ~ "Not rightful regime"
  ))

int3$rightful_regime <- as.factor(int3$rightful_regime)


m_int_1 <- tidy(lm_robust(
  data = int1, y ~ ATT3, clusters = uuid,
  se_type = "stata"
))


m_int_1 <- m_int_1 %>%
  filter(term != "(Intercept)") %>%
  select(term, estimate, conf.low, conf.high)


m_int_2 <- tidy(lm_robust(
  data = int2, y ~ ATT3, clusters = uuid,
  se_type = "stata"
))


m_int_2 <- m_int_2 %>%
  filter(term != "(Intercept)") %>%
  select(term, estimate, conf.low, conf.high)


m_int <- tidy(lm_robust(
  data = int3, y ~ ATT3 * rightful_regime, clusters = uuid,
  se_type = "stata"
))

m_int <- setDT(m_int)
m_int <- m_int[grepl(":", m_int$term), ]
m_int$term <- gsub(":rightful_regimeRightful regime", "", m_int$term, fixed = T)


m_int$attribute <- (str_extract(m_int$term, "ATT[1-9]"))
m_int$term <- gsub("ATT[1-9]", "", m_int$term)


factors <- pivot_longer(cj_tidy, c("ATT3"), names_to = "attribute", values_to = "term") %>%
  select(term, attribute) %>%
  distinct() %>%
  arrange(attribute, term)

m_int <- merge(m_int, factors, by = c("attribute", "term"), all = TRUE)
m_int[["estimate"]][is.na(m_int[["estimate"]])] <- 0
m_int <- setDT(m_int)
m_int[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int[estimate == 0, term := paste(term, ")", sep = "")]

m_int_1$attribute <- (str_extract(m_int_1$term, "ATT[1-9]"))
m_int_1$term <- gsub("ATT[1-9]", "", m_int_1$term)

m_int_1 <- merge(m_int_1, factors, by = c("attribute", "term"), all = TRUE)
m_int_1[["estimate"]][is.na(m_int_1[["estimate"]])] <- 0
m_int_1 <- setDT(m_int_1)
m_int_1[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int_1[estimate == 0, term := paste(term, ")", sep = "")]


m_int_1 <- m_int_1 %>%
  mutate(abs = abs(estimate)) %>%
  group_by(attribute) %>%
  arrange(abs, .by_group = TRUE) %>%
  ungroup() %>%
  mutate(order = row_number() * -1) %>%
  select(-abs)

m_int_2$attribute <- (str_extract(m_int_2$term, "ATT[1-9]"))
m_int_2$term <- gsub("ATT[1-9]", "", m_int_2$term)

m_int_2 <- merge(m_int_2, factors, by = c("attribute", "term"), all = TRUE)
m_int_2[["estimate"]][is.na(m_int_2[["estimate"]])] <- 0
m_int_2 <- setDT(m_int_2)
m_int_2[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int_2[estimate == 0, term := paste(term, ")", sep = "")]


m_int_2 <- m_int_2 %>%
  arrange(match(m_int_2$term, m_int_1$term)) %>%
  mutate(order = row_number() * -1)

m_int <- m_int %>%
  arrange(match(m_int$term, m_int_1$term)) %>%
  mutate(order = row_number() * -1)


m_int_1 <- m_int_1 %>%
  mutate(cond = "Rightful regime")

m_int_2 <- m_int_2 %>%
  mutate(cond = "No rightful regime")

m_int_cond <- rbind(m_int_1, m_int_2)

m_int_cond$cond <- factor(m_int_cond$cond)

m_int_cond$order <- factor(m_int_cond$order)

m_int$order <- factor(m_int$order)

# print(xtable(m_int), include.rownames=FALSE)

## Figure 6c ----------------------

p <- ggplot(m_int_cond, aes(y = order, x = estimate, shape = cond)) +
  xlim(-0.25, 0.15) +
  geom_point(size = 2, position = position_dodge(width = -1)) +
  plexi() +
  geom_linerange(data = m_int_cond, aes(xmin = conf.low, xmax = conf.high, y = order), position = position_dodge(width = -1), key_glyph = "path") +
  facet_grid(attribute ~ ., scales = "free_y", space = "free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks = m_int_cond$order, labels = m_int_cond$term) +
  ylab("") +
  theme(strip.text.y = element_text(angle = 0)) +
  xlab("") +
  geom_vline(xintercept = 0, size = .5, colour = "black", linetype = "dotted") +
  theme(
    strip.background = element_blank(),
    strip.text.y = element_blank()
  )


p3 <- ggplot(m_int, aes(y = order, x = estimate)) +
  xlim(-0.1, 0.1) +
  geom_point(size = 2) +
  plexi() +
  geom_segment(data = m_int, aes(x = conf.low, xend = conf.high, y = order, yend = order)) +
  facet_grid(attribute ~ ., scales = "free_y", space = "free", labeller = as_labeller(att_names)) +
  theme(strip.text.y = element_text(angle = 0)) +
  xlab("\nAMCE") +
  geom_vline(xintercept = 0, size = .5, colour = "black", linetype = "dotted") +
  scale_y_discrete(breaks = m_int$order, labels = m_int$term) +
  ylab("") +
  theme(strip.text.y = element_text(angle = 0)) +
  xlab("") +
  theme(
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank(),
    axis.title.y = element_blank()
  )

p_right <- p + theme(
  legend.title = element_blank(),
  legend.direction = "vertical",
  legend.position = "bottom",
  legend.justification = "left",
  legend.key.height = unit(1, "cm"),
  legend.spacing.y = unit(-0.8, "cm")
) + p3 + ggtitle("Interaction") + plot_annotation(title = "Panel c) Moderation of war context by rightful regime", theme = plexi())


ggsave(p_right, filename = here("figs/fig_6_c.pdf"), width = 9, height = 4, device = cairo_pdf)


# 
# # (AMCE| 1 bn) - (AMCE| 1m)
# 

int1 <- cj_tidy %>%
  filter(ATT6 == "1000 m (1 bn)")

int2 <- cj_tidy %>%
  filter(ATT6 == "1 m")


m_int_1 <- tidy(lm_robust(data = int1, y ~ ATT1 +  ATT2 + ATT3, clusters = uuid, 
                          se_type = "stata"))


m_int_1 <- m_int_1 %>% 
  filter(term != "(Intercept)") %>% 
  select(term, estimate, conf.low, conf.high)


m_int_2 <- tidy(lm_robust(data = int2, y ~ ATT1 +  ATT2 + ATT3, clusters = uuid, 
                          se_type = "stata"))


m_int_2 <- m_int_2 %>% 
  filter(term != "(Intercept)") %>% 
  select(term, estimate, conf.low, conf.high)

m_int <- tidy(lm_robust(data = cj_tidy, y ~ ATT1*ATT6 +  ATT2*ATT6 + 
                          ATT3*ATT6, clusters = uuid, 
                        se_type = "stata"))

m_int <- setDT(m_int)
m_int <- m_int[grepl("ATT61000 m (1 bn)", m_int$term, fixed = T)]
m_int <- m_int[grepl(":", m_int$term),]
m_int$term <- gsub("ATT61000 m (1 bn):", "", m_int$term, fixed = T)
m_int$term <- gsub("ATT1Not democratically elected:ATT61000 m (1 bn)", "ATT1Not democratically elected", m_int$term, fixed = T)


m_int$attribute <- (str_extract(m_int$term, "ATT[1-9]"))
m_int$term <- gsub("ATT[1-9]", "", m_int$term)


factors <- pivot_longer(cj_tidy, c("ATT1", "ATT2", "ATT3"), names_to="attribute", values_to="term") %>% 
  select(term,attribute) %>% 
  distinct() %>% 
  arrange(attribute, term)


m_int <- merge(m_int,factors,  by = c("attribute", "term"), all = TRUE)
m_int[["estimate"]][is.na(m_int[["estimate"]])] <- 0
m_int <- setDT(m_int)
m_int[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int[estimate == 0, term := paste(term, ")", sep = "")]


m_int_1$attribute <- (str_extract(m_int_1$term, "ATT[1-9]"))
m_int_1$term <- gsub("ATT[1-9]", "", m_int_1$term)

m_int_1 <- merge(m_int_1,factors,  by = c("attribute", "term"), all = TRUE)
m_int_1[["estimate"]][is.na(m_int_1[["estimate"]])] <- 0
m_int_1 <- setDT(m_int_1)
m_int_1[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int_1[estimate == 0, term := paste(term, ")", sep = "")]


m_int_1 <- m_int_1 %>% 
  mutate(abs = abs(estimate)) %>% 
  group_by(attribute)  %>% 
  arrange(abs, .by_group = TRUE) %>% 
  ungroup() %>% 
  mutate(order = row_number()*-1) %>% 
  select(-abs)

m_int_2$attribute <- (str_extract(m_int_2$term, "ATT[1-9]"))
m_int_2$term <- gsub("ATT[1-9]", "", m_int_2$term)

m_int_2 <- merge(m_int_2,factors,  by = c("attribute", "term"), all = TRUE)
m_int_2[["estimate"]][is.na(m_int_2[["estimate"]])] <- 0
m_int_2 <- setDT(m_int_2)
m_int_2[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int_2[estimate == 0, term := paste(term, ")", sep = "")]


m_int_2 <- m_int_2 %>% 
  arrange(match(m_int_2$term, m_int_1$term)) %>% 
  mutate(order = row_number()*-1)

m_int <- m_int %>% 
  arrange(match(m_int$term, m_int_1$term)) %>% 
  mutate(order = row_number()*-1)


m_int_1 <- m_int_1 %>% 
  mutate(cond = "1000 m (1 bn)")

m_int_2 <- m_int_2 %>% 
  mutate(cond = "1 m")

m_int_cond <- rbind(m_int_1, m_int_2)

m_int_cond$cond <- factor(m_int_cond$cond)

m_int_cond$order <- factor(m_int_cond$order)
m_int$order <- factor(m_int$order)

# print(xtable(m_int), include.rownames=FALSE)

## Figure A8 ----------------------

p <- ggplot(m_int_cond, aes(y=order,x=estimate, shape = cond)) + xlim(-0.25,0.15) + geom_point(size=2, position = position_dodge(width=-1)) + plexi() +
  geom_linerange(data=m_int_cond, aes(xmin=conf.low,xmax=conf.high, y=order), position = position_dodge(width=-1), key_glyph = "path") +
  facet_grid(attribute~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks=m_int_cond$order,labels=m_int_cond$term)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("") +
  geom_vline(xintercept = 0,size=.5,colour="black",linetype="dotted") + theme(
    strip.background = element_blank(),
    strip.text.y = element_blank()
  ) 



p3 <- ggplot(m_int, aes(y=order,x=estimate)) + xlim(-0.1,0.1) + geom_point(size=2)+ plexi() +
  geom_segment(data=m_int, aes(x=conf.low,xend=conf.high, y=order,yend=order)) +
  facet_grid(attribute~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("\nAMCE") +
  geom_vline(xintercept = 0,size=.5,colour="black",linetype="dotted") +
  scale_y_discrete(breaks=m_int$order,labels=m_int$term)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("")  +
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        axis.title.y = element_blank())


final = p + theme(legend.title = element_blank(), 
          legend.direction = "vertical",
          legend.position = "bottom",
          legend.justification="left",
          legend.key.height = unit(1, "cm"),
          legend.spacing.y = unit(-0.8, 'cm')) + p3 + ggtitle("Interaction")

ggsave(final, filename = here("figs/fig_a_8.pdf"), width = 10, height = 6, device = cairo_pdf)



###

# (AMCE| Large weapons (e.g. tanks, aircraft, ships)) - (AMCE| Military protective equipment)

int1 <- cj_tidy %>% 
  filter(ATT8 == "Large weapons (e.g. tanks, aircraft, ships)")

int2 <- cj_tidy %>% 
  filter(ATT8 == "Military protective equipment")


m_int_1 <- tidy(lm_robust(data = int1, y ~ ATT1 +  ATT2 + ATT3 + ATT5 + ATT6 + ATT7, clusters = uuid, 
                          se_type = "stata"))


m_int_1 <- m_int_1 %>% 
  filter(term != "(Intercept)") %>% 
  select(term, estimate, conf.low, conf.high)


m_int_2 <- tidy(lm_robust(data = int2, y ~ ATT1 +  ATT2 + ATT3 + ATT5 + ATT6 + ATT7, clusters = uuid, 
                          se_type = "stata"))


m_int_2 <- m_int_2 %>% 
  filter(term != "(Intercept)") %>% 
  select(term, estimate, conf.low, conf.high)

m_int <- tidy(lm_robust(data = cj_tidy, y ~ ATT1*ATT8 +  ATT2*ATT8 + 
                          ATT3*ATT8 + ATT5*ATT8 + ATT6*ATT8 + ATT7*ATT8, clusters = uuid, 
                        se_type = "stata"))


m_int <- setDT(m_int)
m_int <- m_int[grepl("ATT8Large weapons (e.g. tanks, aircraft, ships)", m_int$term, fixed = T)]
m_int <- m_int[grepl(":", m_int$term),]
m_int$term <- gsub("ATT8Large weapons (e.g. tanks, aircraft, ships):", "", m_int$term, fixed = T)
m_int$term <- gsub("ATT1Not democratically elected:ATT8Large weapons (e.g. tanks, aircraft, ships)", "ATT1Not democratically elected", m_int$term, fixed = T)


m_int$attribute <- (str_extract(m_int$term, "ATT[1-9]"))
m_int$term <- gsub("ATT[1-9]", "", m_int$term)


factors <- pivot_longer(cj_tidy, c("ATT1", "ATT2", "ATT3", "ATT5", "ATT6", "ATT7"), names_to="attribute", values_to="term") %>% 
  select(term,attribute) %>% 
  distinct() %>% 
  arrange(attribute, term)


m_int <- merge(m_int,factors,  by = c("attribute", "term"), all = TRUE)
m_int[["estimate"]][is.na(m_int[["estimate"]])] <- 0
m_int <- setDT(m_int)
m_int[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int[estimate == 0, term := paste(term, ")", sep = "")]


m_int_1$attribute <- (str_extract(m_int_1$term, "ATT[1-9]"))
m_int_1$term <- gsub("ATT[1-9]", "", m_int_1$term)

m_int_1 <- merge(m_int_1,factors,  by = c("attribute", "term"), all = TRUE)
m_int_1[["estimate"]][is.na(m_int_1[["estimate"]])] <- 0
m_int_1 <- setDT(m_int_1)
m_int_1[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int_1[estimate == 0, term := paste(term, ")", sep = "")]


m_int_1 <- m_int_1 %>% 
  mutate(abs = abs(estimate)) %>% 
  group_by(attribute)  %>% 
  arrange(abs, .by_group = TRUE) %>% 
  ungroup() %>% 
  mutate(order = row_number()*-1) %>% 
  select(-abs)

m_int_2$attribute <- (str_extract(m_int_2$term, "ATT[1-9]"))
m_int_2$term <- gsub("ATT[1-9]", "", m_int_2$term)

m_int_2 <- merge(m_int_2,factors,  by = c("attribute", "term"), all = TRUE)
m_int_2[["estimate"]][is.na(m_int_2[["estimate"]])] <- 0
m_int_2 <- setDT(m_int_2)
m_int_2[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m_int_2[estimate == 0, term := paste(term, ")", sep = "")]


m_int_2 <- m_int_2 %>% 
  arrange(match(m_int_2$term, m_int_1$term)) %>% 
  mutate(order = row_number()*-1)

m_int <- m_int %>% 
  arrange(match(m_int$term, m_int_1$term)) %>% 
  mutate(order = row_number()*-1)


m_int_1 <- m_int_1 %>% 
  mutate(cond = "AMCE|Large weapons")

m_int_2 <- m_int_2 %>% 
  mutate(cond = "AMCE|Military \nprotective equipment")

m_int_cond <- rbind(m_int_1, m_int_2)

m_int_cond$cond <- factor(m_int_cond$cond)

m_int_cond$order <- factor(m_int_cond$order)
m_int$order <- factor(m_int$order)

# print(xtable(m_int), include.rownames=FALSE)

## Figure A9 ----------------------

p <- ggplot(m_int_cond, aes(y=order,x=estimate, shape = cond)) + xlim(-0.25,0.15) + geom_point(size=2, position = position_dodge(width=-1)) + plexi() +
  geom_linerange(data=m_int_cond, aes(xmin=conf.low,xmax=conf.high, y=order), position = position_dodge(width=-1), key_glyph = "path") +
  facet_grid(attribute~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks=m_int_cond$order,labels=m_int_cond$term)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("") +
  geom_vline(xintercept = 0,size=.5,colour="black",linetype="dotted") + theme(
    strip.background = element_blank(),
    strip.text.y = element_blank()
  ) 



p3 <- ggplot(m_int, aes(y=order,x=estimate)) + xlim(-0.1,0.1) + geom_point(size=2)+ plexi() +
  geom_segment(data=m_int, aes(x=conf.low,xend=conf.high, y=order,yend=order)) +
  facet_grid(attribute~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("\nAMCE") +
  geom_vline(xintercept = 0,size=.5,colour="black",linetype="dotted") +
  scale_y_discrete(breaks=m_int$order,labels=m_int$term)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("")  +
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        axis.title.y = element_blank())


final = p + theme(legend.title = element_blank(), 
          legend.direction = "vertical",
          legend.position = "bottom",
          legend.justification="left",
          legend.key.height = unit(1, "cm"),
          legend.spacing.y = unit(-0.8, 'cm')) + p3 + ggtitle("Interaction")

ggsave(final, filename = here("figs/fig_a_9.pdf"), width = 10, height = 8, device = cairo_pdf)


# Substantative Importance/ Predictions --------------------------------------


treat_universe = expand.grid(ATT1 = unique(cj_tidy$ATT1), ATT2 = unique(cj_tidy$ATT2),
                             ATT3 = unique(cj_tidy$ATT3), ATT4 = unique(cj_tidy$ATT4), 
                             ATT5 = unique(cj_tidy$ATT5), ATT6 = unique(cj_tidy$ATT6), 
                             ATT7 = unique(cj_tidy$ATT7), ATT8 = unique(cj_tidy$ATT8), ATT9 = unique(cj_tidy$ATT9))



out_m = lm_robust(y_rating ~ ATT1 + ATT2 + ATT3 + ATT4 + ATT5 + ATT6 + ATT7 + ATT8 + ATT9, data = cj_tidy)

p <- predict(out_m, newdata = treat_universe, se.fit=TRUE, interval="confidence", alpha= 0.05)

treat_universe$pred_out <- p$"fit"[,1]
treat_universe$ci_low <- p$"fit"[,2]
treat_universe$ci_high <- p$"fit"[,3]


p_saudia <- treat_universe %>% 
  filter(ATT1 == "Not democratically elected" & 
           ATT2 == "Dissidents persecuted/incarcerated/tortured" & 
           ATT3 == "Country at war, attacks" & 
           ATT4 == "Important partner" & 
           ATT5 == "A lot of trade of goods" & 
           ATT6 == "1000 m (1 bn)" & 
           ATT7 == "5000" & 
           ATT8 == "Large weapons (e.g. tanks, aircraft, ships)" & 
           ATT9 == "NATO partners (USA, UK, {France/Germany})") %>% 
  select(pred_out)

p_costa <- treat_universe %>% 
  filter(ATT1 == "Democratically elected" & 
           ATT2 == "Human rights respected" & 
           ATT3 == "Peace in the country" & 
           ATT4 == "Not an important partner" & 
           ATT5 == "Little trade of goods" & 
           ATT6 == "1 m" & 
           ATT7 == "100" & 
           ATT8 == "Small arms (e.g. rifles, pistols)" & 
           ATT9 == "Unknown") %>% 
  select(pred_out)


profile <- treat_universe %>%  
  # mutate(dist = abs(pred_out-0.5)) %>% 
  filter(pred_out == min(pred_out) | 
           pred_out == max(pred_out) |
           pred_out == p_saudia$pred_out |
           pred_out == p_costa$pred_out)

profile <- profile %>%  
  unite("Transfer", ATT1:ATT9, remove = T)

profile$Transfer <- gsub("[_]", "; ", profile$Transfer )

profile$pred_out <- round(profile$pred_out, 3)
profile$ci_low <- round(profile$ci_low, 3)
profile$ci_high <- round(profile$ci_high, 3)

profile <- profile %>%  
  unite("CI", ci_low:ci_high, remove = T) 

profile$CI <- gsub("[_]", "-", profile$CI)

profile <- profile %>%arrange(pred_out)


## Table A.5 ---------

print(xtable(profile), include.rownames=FALSE, file= here("tabs/table_a_5_full.tex"))


# By Country

treat_universe_de <- treat_universe
treat_universe_fr <- treat_universe

de <- cj_tidy %>% filter(hCountry == "Germany")
fr <- cj_tidy %>% filter(hCountry == "France")

out_m_de <- lm_robust(data = de, formula = y_rating  ~ ATT1 + ATT2 + ATT3 + ATT4 + ATT5 + ATT6 + ATT7 + ATT8 + ATT9)
out_m_fr <- lm_robust(data = fr, formula = y_rating  ~ ATT1 + ATT2 + ATT3 + ATT4 + ATT5 + ATT6 + ATT7 + ATT8 + ATT9)

p_de <- predict(out_m_de, newdata = treat_universe_de, se.fit=TRUE, interval="confidence", alpha= 0.05)
p_fr <- predict(out_m_fr, newdata = treat_universe_fr, se.fit=TRUE, interval="confidence", alpha= 0.05)


treat_universe_de$pred_out <- p_de$"fit"[,1]
treat_universe_de$ci_low <- p_de$"fit"[,2]
treat_universe_de$ci_high <- p_de$"fit"[,3]

treat_universe_fr$pred_out <- p_fr$"fit"[,1]
treat_universe_fr$ci_low <- p_fr$"fit"[,2]
treat_universe_fr$ci_high <- p_fr$"fit"[,3]


p_saudia_de <- treat_universe_de %>% 
  filter(ATT1 == "Not democratically elected" & 
           ATT2 == "Dissidents persecuted/incarcerated/tortured" & 
           ATT3 == "Country at war, attacks" & 
           ATT4 == "Important partner" & 
           ATT5 == "A lot of trade of goods" & 
           ATT6 == "1000 m (1 bn)" & 
           ATT7 == "5000" & 
           ATT8 == "Large weapons (e.g. tanks, aircraft, ships)" & 
           ATT9 == "NATO partners (USA, UK, {France/Germany})") %>% 
  select(pred_out)

p_costa_de <- treat_universe_de %>% 
  filter(ATT1 == "Democratically elected" & 
           ATT2 == "Human rights respected" & 
           ATT3 == "Peace in the country" & 
           ATT4 == "Not an important partner" & 
           ATT5 == "Little trade of goods" & 
           ATT6 == "1 m" & 
           ATT7 == "100" & 
           ATT8 == "Small arms (e.g. rifles, pistols)" & 
           ATT9 == "Unknown") %>% 
  select(pred_out)


profile_de <- treat_universe_de %>%  
  # mutate(dist = abs(pred_out-0.5)) %>% 
  filter(pred_out == min(pred_out) | 
           pred_out == max(pred_out) |
           pred_out == p_saudia_de$pred_out |
           pred_out == p_costa_de$pred_out)

profile_de <- profile_de %>%  
  unite("Transfer", ATT1:ATT9, remove = T)

profile_de$Transfer <- gsub("[_]", "; ", profile_de$Transfer )

profile_de$pred_out <- round(profile_de$pred_out, 3)
profile_de$ci_low <- round(profile_de$ci_low, 3)
profile_de$ci_high <- round(profile_de$ci_high, 3)

profile_de <- profile_de %>%  
  unite("CI", ci_low:ci_high, remove = T) 

profile_de$CI <- gsub("[_]", "-", profile_de$CI)

profile_de <- profile_de %>%arrange(pred_out)


p_saudia_fr <- treat_universe_fr %>% 
  filter(ATT1 == "Not democratically elected" & 
           ATT2 == "Dissidents persecuted/incarcerated/tortured" & 
           ATT3 == "Country at war, attacks" & 
           ATT4 == "Important partner" & 
           ATT5 == "A lot of trade of goods" & 
           ATT6 == "1000 m (1 bn)" & 
           ATT7 == "5000" & 
           ATT8 == "Large weapons (e.g. tanks, aircraft, ships)" & 
           ATT9 == "NATO partners (USA, UK, {France/Germany})") %>% 
  select(pred_out)

p_high_fr <- treat_universe_fr %>% 
  filter(ATT1 == "Democratically elected" & 
                  ATT2 == "Human rights respected" & 
                  ATT3 == "Peace in the country" & 
                  ATT4 == "Important partner" & 
                  ATT5 == "A lot of trade of goods" &  
                  ATT6 == "1000 m (1 bn)" & 
                  ATT7 == "5000" & 
                  ATT8 == "Military protective equipment" & 
                  ATT9 == "NATO partners (USA, UK, {France/Germany})") %>% 
  select(pred_out)

p_costa_fr <- treat_universe_fr %>% 
  filter(ATT1 == "Democratically elected" & 
           ATT2 == "Human rights respected" & 
           ATT3 == "Peace in the country" & 
           ATT4 == "Not an important partner" & 
           ATT5 == "Little trade of goods" & 
           ATT6 == "1 m" & 
           ATT7 == "100" & 
           ATT8 == "Small arms (e.g. rifles, pistols)" & 
           ATT9 == "Unknown") %>% 
  select(pred_out)


profile_fr <- treat_universe_fr %>%  
  # mutate(dist = abs(pred_out-0.5)) %>% 
  filter(pred_out == min(pred_out) | 
           pred_out == p_high_fr$pred_out |
           pred_out == p_saudia_fr$pred_out |
           pred_out == p_costa_fr$pred_out)


profile_fr <- profile_fr %>%  
  unite("Transfer", ATT1:ATT9, remove = T)

profile_fr$Transfer <- gsub("[_]", "; ", profile_fr$Transfer )

profile_fr$pred_out <- round(profile_fr$pred_out, 3)
profile_fr$ci_low <- round(profile_fr$ci_low, 3)
profile_fr$ci_high <- round(profile_fr$ci_high, 3)

profile_fr <- profile_fr %>%  
  unite("CI", ci_low:ci_high, remove = T) 

profile_fr$CI <- gsub("[_]", "-", profile_fr$CI)

profile_fr <- profile_fr %>%arrange(pred_out)

## Table A.5: GER/FR ---------

print(xtable(profile_fr), include.rownames=FALSE, file= here("tabs/table_a_5_fr.tex"))
print(xtable(profile_de), include.rownames=FALSE, file= here("tabs/table_a_5_de.tex"))

## Deontologists

cj_tidy <- cj_tidy %>%
  mutate(y_reject = ifelse(y_rating <= 3, 1, 0)) %>%
  mutate(y_accept = ifelse(y_rating >= 5, 1, 0)) %>%
  group_by(uuid) %>%
  mutate(share_rej = sum(y_reject) / 12) %>%
  mutate(share_accept = sum(y_accept) / 12) %>%
  mutate(deont_cj = ifelse(share_rej == 1, 1, 0)) %>%
  ungroup()

# CAMCEs

deont <- cj_tidy %>%
  filter(deont_cj == 1)

ndeont <- cj_tidy %>%
  filter(deont_cj == 0)

m2 <-   tidy(lm_robust(data = deont, y ~ ATT1 + ATT2 + ATT3+ ATT4 + ATT5 + ATT6 + ATT7 + ATT8 + ATT9))

m2 <- clean_cj_amce(df = m2, input = cj_tidy)

m3 <-  tidy(lm_robust(data = ndeont, y ~ ATT1 + ATT2 + ATT3+ ATT4 + ATT5 + ATT6 + ATT7 + ATT8 + ATT9))

m3 <- clean_cj_amce(df = m3, input = cj_tidy)


# Differences in CAMCEs

m4 <-  tidy(lm_robust(data = cj_tidy, y ~ ATT1*deont_cj + ATT2*deont_cj + ATT3*deont_cj
                      + ATT4*deont_cj + ATT5*deont_cj + ATT6*deont_cj + ATT7*deont_cj + ATT8*deont_cj + ATT9*deont_cj))


# m4 <-  tidy(lm_robust(data = cj_tidy, y ~ ATT1*de + ATT2*de + ATT3*de
#                       + ATT4*de + ATT5*de + ATT6*de + ATT7*de + ATT8*de + ATT9*de,  cluster = uuid, method = "stata"))

m4  <- setDT(m4)
m4 <- m4[term != "(Intercept)"]
m4$attribute <- (str_extract(m4$term, "ATT[1-9]"))
m4$term <- gsub("ATT[1-9]", "", m4$term)
m4 <- m4[grepl("deont_cj:", m4$term) | term == "Not democratically elected:deont_cj",]
m4$term <- gsub("deont_cj:", "", m4$term)
m4$term <- gsub("Not democratically elected:deont_cj", "Not democratically elected", m4$term)


factors <- pivot_longer(cj_tidy, ATT1:ATT9, names_to="attribute", values_to="term") %>%
  select(term,attribute) %>%
  distinct() %>%
  arrange(attribute, term)


m4 <- merge(m4,factors,  by = c("attribute", "term"), all = TRUE)
m4[["estimate"]][is.na(m4[["estimate"]])] <- 0
m4[estimate == 0, term := paste("(Baseline =", term, sep = " ")]
m4[estimate == 0, term := paste(term, ")", sep = "")]


m4 <- m4[match(m2$term, m4$term),]

m4 <- m4 %>%
  mutate(order = row_number()*-1)

m4$order <- factor(m4$order)

# Figure A.21 ---------

p2 <- ggplot(m2, aes(y=order,x=estimate)) + xlim(-0.25,0.25) + geom_point(size=2)+ plexi() +
  geom_segment(data=m2, aes(x=conf.low,xend=conf.high, y=order,yend=order)) +
  geom_text(aes(label=ifelse(estimate != 0, round(estimate, digits = 3),"")), vjust = 0, nudge_y = 0.3) +
  facet_grid(attribute~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks=m2$order,labels=m2$term)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("") +
  geom_vline(xintercept = 0,size=.5,colour="black",linetype="dotted") + theme(
    strip.background = element_blank(),
    strip.text.y = element_blank()
  )



p3 <- ggplot(m3, aes(y=order,x=estimate)) + xlim(-0.25,0.25) + geom_point(size=2)+ plexi() +
  geom_segment(data=m3, aes(x=conf.low,xend=conf.high, y=order,yend=order)) +
  geom_text(aes(label=ifelse(estimate != 0, round(estimate, digits = 3),"")), vjust = 0, nudge_y = 0.3) +
  facet_grid(attribute~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks=m3$order,labels=m3$term)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("\nAMCE") +
  geom_vline(xintercept = 0,size=.5,colour="black",linetype="dotted") + theme(axis.text.y = element_blank(),
                                                                              axis.ticks.y = element_blank(),
                                                                              axis.title.y = element_blank() ) +
  theme(
    strip.background = element_blank(),
    strip.text.y = element_blank()
  )




p4 <- ggplot(m4, aes(y=order,x=estimate)) + xlim(-0.25,0.25) + geom_point(size=2)+ plexi() +
  geom_segment(data=m4, aes(x=conf.low,xend=conf.high, y=order,yend=order)) +
  geom_text(aes(label=ifelse(estimate != 0, round(estimate, digits = 3),"")), vjust = 0, nudge_y = 0.3) +
  facet_grid(attribute~., scales="free_y", space="free", labeller = as_labeller(att_names)) +
  scale_y_discrete(breaks=m4$order,labels=m4$term)+ ylab("") +
  theme(strip.text.y=element_text(angle=0))  +
  xlab("") +
  geom_vline(xintercept = 0,size=.5,colour="black",linetype="dotted") + theme(axis.text.y = element_blank(),
                                                                              axis.ticks.y = element_blank(),
                                                                              axis.title.y = element_blank() )



final = p2 + ggtitle("Deontologists") + p3 + ggtitle("Consequentialists") + p4 + ggtitle("Difference in CAMCEs")

ggsave(final, filename = here("figs/fig_a_7.pdf"), width = 18, height = 11, device = cairo_pdf)

ui_done("Done with conjoint analysis.")

}